package com.shz.utils;

public class SnowflakeIdGenerator {

    private final long epoch = 1609459200000L; // 2021-01-01 00:00:00
    private final long workerIdPartBits = 5L;
    private final long sequencePartBits = 12L;

    private final long maxWorkerId = -1L ^ (-1L << workerIdPartBits);
    private final long workerIdShift = sequencePartBits;
    private final long timestampShift = sequencePartBits + workerIdPartBits;
    private final long sequenceMask = -1L ^ (-1L << sequencePartBits);

    private long workerId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    public SnowflakeIdGenerator(long workerId) {
        if (workerId < 0 || workerId > maxWorkerId) {
            throw new IllegalArgumentException(String.format("Worker ID must be between 0 and %d", maxWorkerId));
        }
        this.workerId = workerId;
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format("Clock moved backwards. Refusing to generate ID. Last timestamp: %d, current timestamp: %d",
                            lastTimestamp, timestamp)
            );
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - epoch) << timestampShift) | (workerId << workerIdShift) | sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }

    // 使用单例模式保证全局唯一实例
    private static class SingletonHolder {
        private static final SnowflakeIdGenerator INSTANCE = new SnowflakeIdGenerator(1); // Worker ID
    }

    public static long getGlobalId() {
        return SingletonHolder.INSTANCE.nextId();
    }
}